package com.ruoyi.system.service.impl;

import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfReader;
import com.ruoyi.common.exception.user.TemplateException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.file.FastDFSUtil;
import com.ruoyi.system.domain.SysCertificateSchool;
import com.ruoyi.system.domain.SysOrganization;
import com.ruoyi.system.domain.SyseEventsPosted;
import com.ruoyi.system.mapper.SysCertificateSchoolMapper;
import com.ruoyi.system.mapper.SysEventsPostedMapper;
import com.ruoyi.system.mapper.SysOrganizationMapper;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.ISysCertificateSchoolService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author 柳
 * @Date 2021/5/10
 * @Description TODO
 * 校园证书信息
 */
@Service
public class SysCertificateSchoolServiceImpl implements ISysCertificateSchoolService {

    @Autowired
    private SysCertificateSchoolMapper sysCertificateSchoolMapper;

    @Autowired
    private SysEventsPostedMapper sysEventsPostedMapper;

    @Autowired
    private FastDFSUtil fastDFSUtil;

    @Autowired
    private ISysUserService sysUserService;


    @Autowired
    private SysOrganizationMapper sysOrganizationMapper;

    /**
     *  查询所有学校证书信息(含综合查询)
     * @param sysCertificateSchool
     * @return
     */
    @Override
    public List<SysCertificateSchool> querySysCertificateSchools(SysCertificateSchool sysCertificateSchool) {
        return sysCertificateSchoolMapper.querySysCertificateSchools(sysCertificateSchool);
    }

    /**
     * 根据证书id删除学校证书信息
     * @param certificateid
     */
    @Override
    public void deleteSysCertificateSchool(Integer certificateid) {
        sysCertificateSchoolMapper.deleteSysCertificateSchool(certificateid);
    }

    /**
     * 查询是否重复颁发学校证书
     * @param sysCertificateSchool
     * @return
     */
    @Override
    public Integer queryCertificateSchoolIsNull(SysCertificateSchool sysCertificateSchool) {
        return sysCertificateSchoolMapper.queryCertificateSchoolIsNull(sysCertificateSchool);
    }

    /**
     * 颁发校园证书
     * @param sysCertificateSchool
     */
    @Override
    public void saveSysCertificateSchool(SysCertificateSchool sysCertificateSchool) throws TemplateException {
        //数据准备
        Integer cid=0;
        //获取当前时间转换字符串用于证书编号
        Date date=new Date();
        SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");
        String format = sdf.format(date);

        //根据大赛id获取大赛信息
        SyseEventsPosted syseEventsPosted = sysEventsPostedMapper.selectById(sysCertificateSchool.getEpid());

        Integer count = sysCertificateSchoolMapper.querySysCertificateSchoolLately();
        if(count!=null){
            cid=count;
        }

        SysOrganization sysOrganization = sysOrganizationMapper.querySysOrganizationById(sysCertificateSchool.getOrganizationid());

        if (sysOrganization == null ||
                sysOrganization.getOrganizationname() == null ||
                sysOrganization.getFile() == null ||
                sysOrganization.getFilemsg() == null ||
                sysOrganization.getSeal() == null
        ) {
            throw new TemplateException(400, "当前学校没有在平台登记证书模板, 请联系平台管理员！");
        }
        //这里是选择某个模板
        String templateName = "templateschool";
        String templateImage ="获奖证书模板.png";


        String baseUrl = System.getProperty("user.dir");
        baseUrl = baseUrl.replaceAll("\\\\", "/");

        //组织数据填充到模板中
        Map<String, Object> paramMap = new HashMap<String, Object>();
        //这里是给具体的某些字段赋值
        paramMap.put("school", sysCertificateSchool.getSchoolrName());
        paramMap.put("organizations",sysOrganization.getOrganizationname());
        paramMap.put("issuetime", DateUtils.toChinese(sysCertificateSchool.getIssuetime()));
        paramMap.put("activity", syseEventsPosted.getEptitle());
        paramMap.put("certificateid", format+(cid+1));
        paramMap.put("organization", sysOrganization.getOrganizationname());
        paramMap.put("file", sysOrganization.getFile());
        paramMap.put("filemsg", sysOrganization.getFilemsg());
        paramMap.put("organizationurl", sysOrganization.getSeal());
        paramMap.put("backgroundurl", "file:///"+baseUrl+"//ruoyi-admin//src//main//resources//zhengshu//image//"+templateImage);

        /**
         * 生成的pdf文件的路径
         */
        String pdfPath = "";
        //生成pdf文件
        try {
            contractHandler(templateName, paramMap);

            pdfPath = fastDFSUtil.uploadFile(new File(System.getProperty("user.dir") + "\\ruoyi-admin\\src\\main\\resources\\zhengshu\\pdf\\pdfDemo.pdf"));
            sysCertificateSchool.setPdfpath(pdfPath);

            String PdfFilePath = fastDFSUtil.getResAccessUrl(sysCertificateSchool.getPdfpath());//文件服务器上pdf文件存放的地址
            int dpi=444;


            File file = null;

            URL urlfile;
            InputStream inputStream = null;
            OutputStream outputStream= null;
            PDDocument pdDocument;
            try {
                file = File.createTempFile("wx_image", ".png");
                //下载
                urlfile = new URL(PdfFilePath);
                inputStream = urlfile.openStream();
                outputStream= new FileOutputStream(file);

                int bytesRead = 0;
                byte[] buffer = new byte[8192];
                while ((bytesRead = inputStream.read(buffer, 0, 8192)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
                pdDocument = PDDocument.load(file);
                PDFRenderer renderer = new PDFRenderer(pdDocument);
                PdfReader reader = new PdfReader(PdfFilePath);
                int pages = reader.getNumberOfPages();// 获取PDF页数
                //System.out.println("PDF page number is:" + pages);
                StringBuffer imgFilePath = null;
                for (int i = 0; i < pages; i++) {
                    File dstFile = new File(PDFIMAGE+".png");
                    BufferedImage image = renderer.renderImageWithDPI(i, dpi);
                    ImageIO.write(image, "png", dstFile);// PNG
                    String s = fastDFSUtil.uploadFile(dstFile);
                    //System.out.println(fastDFSUtil.getResAccessUrl(s));
                    sysCertificateSchool.setImage_url(fastDFSUtil.getResAccessUrl(s));
                }
                System.out.println("PDF文档转PNG图片成功！");
                //颁发证书(添加证书信息)
                sysCertificateSchoolMapper.saveSysCertificateSchool(sysCertificateSchool);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (null != outputStream) {
                        outputStream.close();
                    }
                    if (null != inputStream) {
                        inputStream.close();
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }











    private static final String TEMPLATE = System.getProperty("user.dir")+"\\ruoyi-admin\\src\\main\\resources\\zhengshu\\ftl";//模板存储路径
    private static final String CONTRACT = System.getProperty("user.dir")+"\\ruoyi-admin\\src\\main\\resources\\zhengshu\\pdf";
    private static final String PDFIMAGE = System.getProperty("user.dir")+"\\ruoyi-admin\\src\\main\\resources\\zhengshu\\pdfimage";//模板存储路径

    private static final String IMAGENAME = "pdfDemo";//pdf文件名
    private static final String PDFNAME = "pdfDemo";//pdf文件名
    private static final String HTMLNAME = "pdfDemo";//html文件名



    public void contractHandler(String templateName,
                                Map<String, Object> paramMap) throws Exception {
        // 获取本地模板存储路径、合同文件存储路径
        String templatePath = TEMPLATE;
        String contractPath = CONTRACT;
        // 组装html和pdf合同的全路径URL
        String localHtmlUrl = contractPath + HTMLNAME + ".html";
        String localPdfPath = contractPath + "/";
        // 判断本地路径是否存在如果不存在则创建
        File localFile = new File(localPdfPath);
        if (!localFile.exists()) {
            localFile.mkdirs();
        }
        String localPdfUrl = localFile + "/" + PDFNAME + ".pdf";
        templateName = templateName + ".ftl";
        htmHandler(templatePath, templateName, localHtmlUrl, paramMap);// 生成html合同
        pdfHandler(localHtmlUrl, localPdfUrl);// 根据html合同生成pdf合同
        deleteFile(localHtmlUrl);// 删除html格式合同

        System.out.println("PDF生成成功");
    }

    /**
     * 生成HTML格式合同
     * @param templatePath
     * @param templateName
     * @param htmUrl
     * @param paramMap
     * @throws Exception
     */
    private static void htmHandler(String templatePath, String templateName,
                                   String htmUrl, Map<String, Object> paramMap) throws Exception {
        Configuration cfg = new Configuration();
        cfg.setDefaultEncoding("UTF-8");
        cfg.setDirectoryForTemplateLoading(new File(templatePath));

        Template template = cfg.getTemplate(templateName);

        File outHtmFile = new File(htmUrl);

        Writer out = new BufferedWriter(new OutputStreamWriter(
                new FileOutputStream(outHtmFile),"UTF-8"));
        template.process(paramMap, out);

        out.close();
    }

    /**
     * 生成PDF格式合同
     * @param htmUrl
     * @param pdfUrl
     * @throws Exception
     * @throws IOException
     */
    private static void pdfHandler(String htmUrl, String pdfUrl)
            throws Exception, IOException {
        File htmFile = new File(htmUrl);
        File pdfFile = new File(pdfUrl);

        String url = htmFile.toURI().toURL().toString();

        OutputStream os = new FileOutputStream(pdfFile);

        ITextRenderer renderer = new ITextRenderer();

        //renderer.getSharedContext().setBaseURL("file:/"+"E:/IdeaProjects/demo/src/main/resources/image/");

        renderer.setDocument(url);


        ITextFontResolver fontResolver = renderer
                .getFontResolver();

        try {
            fontResolver.addFont(System.getProperty("user.dir")+"\\ruoyi-admin\\src\\main\\resources\\zhengshu\\font\\simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        } catch (Exception e) {
            e.printStackTrace();
        }

        renderer.layout();
        try {
            renderer.createPDF(os);
        } catch (Exception e) {
            e.printStackTrace();
        }
        os.close();
    }

    /**
     * 删除HTML文件
     * @param fileUrl
     */
    private static void deleteFile(String fileUrl) {
        File file = new File(fileUrl);
        file.delete();
    }



    private static boolean createDirectory(String folder) {
        File dir = new File(folder);
        if (dir.exists()) {
            return true;
        } else {
            return dir.mkdirs();
        }
    }
}
